package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//权限拦截器
@Component      //将拦截器注入到ioc容器
public class LoginCheckInterceptor implements HandlerInterceptor {

    //在访问控制器之前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session域中的对象
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //2.判断employee是否为空,(登录状态)
        if (employee == null) {
            //若为空,设置前端响应常量
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            //手动设置转为json
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(resultInfo);
            //向前端发送response响应
            response.setContentType("application/json;charset=utf-8");  //设置响应字符集为json格式
            response.getWriter().write(json);
            //拦截
            return false;
        }
        //若不为空,则登陆成功,放行
        EmployeeHolder.set(employee);       //employee对象存入当前线程
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();        //删除当前线程中的employee对象
    }
}
